package com.jalopaba.android.Tempodroid;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class Temporization extends Activity {
	public static String LOG_TAG = "Tempodroid";
	
	private int totalSeconds;
	
	private TextView textSeconds;
	private ProgressBar progressBar;
	private boolean isRunning = false;
	
	class TempoTask extends AsyncTask<Void, Integer, Void> {
		private int max;
		
		public TempoTask(int maxSeconds) {
			super();
			this.max = maxSeconds;
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			Log.d(LOG_TAG, "tempoTask started");
			for (int i = 0; i < max && isRunning; i++) {
				SystemClock.sleep(1000);
				publishProgress(i+1);
			}
			Log.d(LOG_TAG, "tempoTask finished");
			return null;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			// Called on the UI thread
			int now = values[0];
			progressBar.setProgress(now * 100);
			textSeconds.setText(String.valueOf(now) + "/" + max);
		}
		
		@Override
		protected void onPostExecute(Void result) {
			Toast.makeText(Temporization.this.getApplicationContext(), 
					Temporization.this.getApplication().getString(R.string.countFinished), 
					Toast.LENGTH_SHORT).show();
		}
	}	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.temporization);

		Bundle bundle = getIntent().getExtras();
		totalSeconds = Integer.parseInt(bundle.getString("seconds"));
		
		textSeconds = (TextView) findViewById(R.id.textSeconds);
		textSeconds.setText("0/" + totalSeconds);
		
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		progressBar.setMax(totalSeconds * 100);
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		progressBar.setProgress(0);

		isRunning = true;
		new TempoTask(totalSeconds).execute();
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		Log.d(LOG_TAG, "Stopping temporization activity");
		isRunning = false;
	}
}
